package edu.zhangxu.servlet;

import edu.zhangxu.dao.ProblemDao;
import edu.zhangxu.dao.ProblemDaoImp;
import edu.zhangxu.pojo.Problem;
import edu.zhangxu.util.JDBCUtils;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Connection;

public class ProblemDesc extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");

        resp.setContentType("text/html;charset=utf-8");
        resp.setHeader("Access-Control-Allow-Origin", "*"); // 允许跨域访问
        Connection con = null;
        Problem problem;
        ProblemDao dao = new ProblemDaoImp();
        JSONObject jo = null;
        try {
            con = JDBCUtils.getConnection();
            problem = dao.getProblemByName(con, name);
            jo = JSONObject.fromObject(problem);
        } catch (Exception e) {
            e.printStackTrace();
            jo = JSONObject.fromObject(e);
        } finally {
            JDBCUtils.closeConnection(con, null);
            resp.getWriter().print(jo);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

/**
 *         InputStream ins=getServletContext().getResourceAsStream("/problemSet/"+name+"/"+name+".html");
 *         if(ins != null) {
 *             OutputStream out= resp.getOutputStream();
 *             byte[] bys=new byte[1024];
 *             int len=0;
 *             while((len=ins.read(bys))>0){
 *                 out.write(bys, 0, len);
 *                 out.flush();
 *             }
 *         } else {
 *             PrintWriter out = resp.getWriter();
 *             out.print("暂无题目描述");
 *         }
 */
